package com.leijie.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Nio buffer三个重要的属性练习
 * postion
 * limit
 * capacity
 */
public class NioTest5 {

    public static void main(String[] args) throws Exception {
        //查看 postion limit catacity值得变化
//        ByteBuffer buffer = ByteBuffer.allocate(10);
//        System.out.println(buffer);
//        buffer.put((byte) 'a');
//        System.out.println(buffer);
//        buffer.flip();
//        System.out.println(buffer);
//        buffer.put((byte) 'a');
//        buffer.put((byte) 'b');
//        System.out.println(buffer);

        FileInputStream inputStream = new FileInputStream("input.txt");
        FileOutputStream outputStream = new FileOutputStream("out.txt");

        FileChannel inputChannel = inputStream.getChannel();
        FileChannel outputChannel = outputStream.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(512);

        while (true){
            //如果不加clear 会出现什么情况？？
            //buffer 不clear postion和limit的值第二次循环换变成一样 inputChannel.read方法会判断这个值 结果会返回0 读不到任何内容
//            buffer.clear();

            int read = inputChannel.read(buffer);

            if (read == -1)break;

            buffer.flip();

            outputChannel.write(buffer);

        }
        inputChannel.close();
        outputChannel.close();
    }

}
